Page({
  data: {
    yesterdayBloodPressure: 0,
    yesterdayBloodSugar: 0,
    yesterdayHeartRate: 0,
    yesterdayLungCapacity: 0,
    yesterdayWeight: 0,
    todayBloodPressure: 0,
    todayBloodSugar: 0,
    todayHeartRate: 0,
    todayLungCapacity: 0,
    todayWeight: 0,
    bloodPressureDifference: 0,
    bloodSugarDifference: 0,
    heartRateDifference: 0,
    lungCapacityDifference: 0,
    weightDifference: 0
  },

  onLoad: function () {
    // 页面加载时获取昨天的数据
    this.getYesterdayData();
  },

  // 输入今日血压
  inputTodayBloodPressure: function (e) {
    this.setData({
      todayBloodPressure: e.detail.value
    });
    this.calculateDifference('bloodPressure');
  },

  // 输入今日血糖
  inputTodayBloodSugar: function (e) {
    this.setData({
      todayBloodSugar: e.detail.value
    });
    this.calculateDifference('bloodSugar');
  },

  // 输入今日心率
  inputTodayHeartRate: function (e) {
    this.setData({
      todayHeartRate: e.detail.value
    });
    this.calculateDifference('heartRate');
  },

  // 输入今日肺活量
  inputTodayLungCapacity: function (e) {
    this.setData({
      todayLungCapacity: e.detail.value
    });
    this.calculateDifference('lungCapacity');
  },

  // 输入今日体重
  inputTodayWeight: function (e) {
    this.setData({
      todayWeight: e.detail.value
    });
    this.calculateDifference('weight');
  },

  calculateDifference: function (key) {
    let todayValue = this.data['today' + key.charAt(0).toUpperCase() + key.slice(1)];
    let yesterdayValue = this.data['yesterday' + key.charAt(0).toUpperCase() + key.slice(1)];
    let difference = todayValue - yesterdayValue;
    this.setData({
      [key + 'Difference']: difference
    });

    // 保存今日数据作为明天的昨日数据
    wx.setStorageSync(key + 'Yesterday', todayValue);
  },

  getYesterdayData: function () {
    this.setData({
      yesterdayBloodPressure: wx.getStorageSync('bloodPressureYesterday') || 0,
      yesterdayBloodSugar: wx.getStorageSync('bloodSugarYesterday') || 0,
      yesterdayHeartRate: wx.getStorageSync('heartRateYesterday') || 0,
      yesterdayLungCapacity: wx.getStorageSync('lungCapacityYesterday') || 0,
      yesterdayWeight: wx.getStorageSync('weightYesterday') || 0
    });
  }
})